package com.significantfiles.snapshot.engine.io;

import static com.significantfiles.snapshot.config.SnapshotConfig.WRITER_THREAD_SLEEP;

import java.util.concurrent.ArrayBlockingQueue;

import com.significantfiles.snapshot.engine.structure.EndOfQueueEntity;
import com.significantfiles.snapshot.engine.structure.IEntity;

public class SnapshotWriter implements Runnable {

	private final Snapshot snapshotDef;

	private final ArrayBlockingQueue<IEntity> queue = new ArrayBlockingQueue<IEntity>(
			100);

	private boolean isFinished;

	public SnapshotWriter(final Snapshot snapshotDefinition) {
		if (snapshotDefinition == null)
			throw new NullPointerException();

		this.snapshotDef = snapshotDefinition;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(WRITER_THREAD_SLEEP);
			} catch (final InterruptedException e) {
				final String errLogMsg = "A SnapshotWriter-thread can't sleep.";
				throw new SnapshotWriterIOException(errLogMsg);
			}
			
			final IEntity entity = this.queue.poll();

			if (entity instanceof EndOfQueueEntity) {
//				final Thread thread = Thread.currentThread();
//				thread.interrupt();
				
				return;
			}

			if (entity == null)
				continue;

			System.out.println(">>> write element: id = " + entity.getId());
		}
	}

	public void pushEntity(final IEntity entity) throws InterruptedException {
		this.queue.put(entity);
	}

	public synchronized void endWriter() {
        try {
			this.queue.put(EndOfQueueEntity.INSTANCE);
		} catch (final InterruptedException e) {
			e.printStackTrace();
		}
	}

}
